package com.gy.zpchat.ui.search.adapter.holder;

import android.app.Activity;
import android.net.Uri;
import android.os.Build;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import im.zego.zim.callback.ZIMMediaDownloadedCallback;
import im.zego.zim.entity.ZIMCommandMessage;
import im.zego.zim.entity.ZIMError;
import im.zego.zim.entity.ZIMMediaMessage;
import im.zego.zim.entity.ZIMSystemMessage;
import im.zego.zim.entity.ZIMTextMessage;
import im.zego.zim.enums.ZIMMediaFileType;
import im.zego.zim.enums.ZIMMessageReceiptStatus;
import im.zego.zim.enums.ZIMMessageSentStatus;
import im.zego.zim.enums.ZIMMessageType;
import com.gy.zpchat.R;
import com.gy.zpchat.SDKManager;
import com.gy.zpchat.entity.SearchInfo;
import com.gy.zpchat.ui.search.adapter.OnItemClickListener;

import java.io.File;
import java.nio.charset.StandardCharsets;

public class BaseViewHolder extends RecyclerView.ViewHolder {

    private static final String TAG = "ChatAcceptViewHolder";
    private Activity activity;
    private final OnItemClickListener onItemClickListener;
    private RelativeLayout.LayoutParams layoutParams;
    public TextView contentTextView, userIDTextView;
    public RelativeLayout rightViewLayout;
    private SearchInfo messageInfo;
    private ImageView imageView;
    private ImageView sentStateImageView;
    private TextView receiptStatusView;
    private ImageView fileTypeIcon;
    private ProgressBar loadingBar;
    public BaseViewHolder(ViewGroup parent, int res, Activity activity,
                          OnItemClickListener onItemClickListener) {
        super(LayoutInflater.from(parent.getContext()).inflate(res, parent, false));
        findViewByIds(itemView);
        this.activity = activity;
        this.onItemClickListener = onItemClickListener;
    }

    private void findViewByIds(View itemView) {
        loadingBar = itemView.findViewById(R.id.loading);
        rightViewLayout = itemView.findViewById(R.id.relativeLayout);
        contentTextView = itemView.findViewById(R.id.content);
        userIDTextView = itemView.findViewById(R.id.user_id);
        sentStateImageView = itemView.findViewById(R.id.sent_state);
        imageView = itemView.findViewById(R.id.image);
        fileTypeIcon = itemView.findViewById(R.id.file_type_icon);
        receiptStatusView = itemView.findViewById(R.id.tv_receipt);
    }

    public void setMessageInfo(SearchInfo info) {
        messageInfo = info;
        String senderUserID = messageInfo.getZIMMessage().getSenderUserID();
        userIDTextView.setText(senderUserID);
        fileTypeIcon.setVisibility(View.GONE);
        imageView.setVisibility(View.GONE);
        imageView.setBackground(null);
        imageView.setImageDrawable(null);
        contentTextView.setText("");

        if (messageInfo.getZIMMessage().getSentStatus() == ZIMMessageSentStatus.FAILED) {
            sentStateImageView.setVisibility(View.VISIBLE);
            if (loadingBar != null) {
                loadingBar.setVisibility(View.GONE);
            }
        } else if (messageInfo.getZIMMessage().getSentStatus() == ZIMMessageSentStatus.SENDING) {
            if (loadingBar != null) {
                loadingBar.setVisibility(View.VISIBLE);
            }
            sentStateImageView.setVisibility(View.GONE);
        } else {
            if (loadingBar != null) {
                loadingBar.setVisibility(View.GONE);
            }
            sentStateImageView.setVisibility(View.GONE);
        }
        if (receiptStatusView != null) {
            if (info.getZimMessageReceiptStatus() != ZIMMessageReceiptStatus.NONE) {
                receiptStatusView.setVisibility(View.VISIBLE);
                if (info.getZimMessageReceiptStatus() == ZIMMessageReceiptStatus.DONE) {
                    receiptStatusView.setText("✅");
                } else if (info.getZimMessageReceiptStatus() ==
                           ZIMMessageReceiptStatus.PROCESSING) {
                    if (info.getReceiptUnreadMemberCount() != 0) {
                        receiptStatusView.setText(
                            String.valueOf(info.getReceiptUnreadMemberCount()));
                    } else {
                        receiptStatusView.setText("\uD83D\uDFE2");
                    }
                } else {
                    receiptStatusView.setText("❌");
                }
            }
        }
        if (messageInfo.getZIMMessage().getType() == ZIMMessageType.TEXT) {
            contentTextView.setText(
                Html.fromHtml(((ZIMTextMessage)messageInfo.getZIMMessage()).message));
        } else if (messageInfo.getZIMMessage().getType() == ZIMMessageType.SYSTEM) {
            contentTextView.setText(
                Html.fromHtml(((ZIMSystemMessage)messageInfo.getZIMMessage()).message));
        } else if (messageInfo.getZIMMessage().getType() == ZIMMessageType.COMMAND) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                contentTextView.setText(
                    "[command]: " + Html.fromHtml(new String(
                                        ((ZIMCommandMessage)messageInfo.getZIMMessage()).message,
                                        StandardCharsets.UTF_8)));
            }
        } else if (messageInfo.getZIMMessage().getType() == ZIMMessageType.IMAGE ||
                   messageInfo.getZIMMessage().getType() == ZIMMessageType.VIDEO) {
            ZIMMediaMessage zimMessage = (ZIMMediaMessage)messageInfo.getZIMMessage();
            imageView.setVisibility(View.VISIBLE);
            imageView.setTag(R.id.image, messageInfo.getZIMMessage());

            SDKManager.sharedInstance().downloadMediaFile(
                (ZIMMediaMessage)messageInfo.getZIMMessage(), ZIMMediaFileType.ORIGINAL_FILE,
                new ZIMMediaDownloadedCallback() {
                    @Override
                    public void onMediaDownloaded(ZIMMediaMessage message, ZIMError errorInfo) {
                        ZIMMediaMessage zimMediaMessage =
                            (ZIMMediaMessage)imageView.getTag(R.id.image);
                        if (message.getLocalMessageID() == zimMediaMessage.getLocalMessageID()) {
                            if (!activity.isDestroyed()) {
                                imageView.setTag(R.id.image, message);
                                messageInfo.setZIMMessage(message);
                                Glide.with(activity)
                                    .load(Uri.fromFile(
                                        new File(((ZIMMediaMessage)message).getFileLocalPath())))
                                    .centerCrop()
                                    .into(imageView);
                            }
                        }
                    }

                    @Override
                    public void onMediaDownloadingProgress(
                        ZIMMediaMessage message, long currentFileSize, long totalFileSize) {}
                });
            contentTextView.setText("");
            if (messageInfo.getZIMMessage().getType() == ZIMMessageType.VIDEO) {
                fileTypeIcon.setVisibility(View.VISIBLE);
            }
        } else if (messageInfo.getZIMMessage().getType() == ZIMMessageType.AUDIO ||
                   messageInfo.getZIMMessage().getType() == ZIMMessageType.FILE) {
            imageView.setImageResource(R.drawable.file_fill);
            imageView.setTag(R.id.image, messageInfo.getZIMMessage());
            imageView.setVisibility(View.VISIBLE);
            SDKManager.sharedInstance().downloadMediaFile(
                (ZIMMediaMessage)messageInfo.getZIMMessage(), ZIMMediaFileType.ORIGINAL_FILE,
                new ZIMMediaDownloadedCallback() {
                    @Override
                    public void onMediaDownloaded(ZIMMediaMessage message, ZIMError errorInfo) {
                        ZIMMediaMessage zimMediaMessage =
                            (ZIMMediaMessage)imageView.getTag(R.id.image);
                        if (message.getLocalMessageID() == zimMediaMessage.getLocalMessageID()) {
                            if (!activity.isDestroyed()) {
                                imageView.setTag(R.id.image, message);
                                messageInfo.setZIMMessage(message);
                            }
                        }
                    }

                    @Override
                    public void onMediaDownloadingProgress(
                        ZIMMediaMessage message, long currentFileSize, long totalFileSize) {}
                });
        }
    }

    public void release() {
        if (imageView != null) {
            imageView.setOnClickListener(null);
        }
        if (rightViewLayout != null) {
            rightViewLayout.setOnLongClickListener(null);
        }
        activity = null;
    }
}
